package icu.cqcai.xinsi.config;

import icu.cqcai.xinsi.util.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.ArrayList;

/**
 * JWT认证过滤器
 * 用于验证请求中的JWT token并设置认证信息
 */
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, 
                                  FilterChain filterChain) throws ServletException, IOException {

        String requestPath = request.getRequestURI();
        
        // 跳过不需要认证的路径
        if (shouldSkipAuthentication(requestPath)) {
            filterChain.doFilter(request, response);
            return;
        }

        String token = getTokenFromRequest(request);
        
        if (token != null && SecurityContextHolder.getContext().getAuthentication() == null) {
            try {
                if (jwtUtil.validateToken(token)) {
                    String username = jwtUtil.getUsernameFromToken(token);
                    
                    if (username != null) {
                        // 创建认证对象
                        UsernamePasswordAuthenticationToken authentication = 
                            new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        
                        // 设置认证信息到安全上下文
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                        
                        logger.debug("JWT认证成功: " + username);
                    }
                }
            } catch (Exception e) {
                logger.error("JWT认证过程发生错误: " + e.getMessage());
            }
        }

        filterChain.doFilter(request, response);
    }

    /**
     * 从请求中提取JWT token
     * 优先从Authorization header获取，然后从cookie获取
     */
    private String getTokenFromRequest(HttpServletRequest request) {
        // 从Authorization header获取
        String bearerToken = request.getHeader("Authorization");
        if (bearerToken != null && bearerToken.startsWith("Bearer ")) {
            String token = bearerToken.substring(7);
            return token;
        }
        
        // 从cookie获取（用于页面访问）
        jakarta.servlet.http.Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (jakarta.servlet.http.Cookie cookie : cookies) {
                if ("token".equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        
        return null;
    }

    /**
     * 判断是否应该跳过认证
     */
    private boolean shouldSkipAuthentication(String requestPath) {
        // 静态资源
        if (requestPath.startsWith("/css/") || requestPath.startsWith("/js/") || 
            requestPath.startsWith("/img/") || requestPath.startsWith("/vendors/") ||
            requestPath.startsWith("/static/")) {
            return true;
        }
        
        // API接口（注册、登录等）
        if (requestPath.startsWith("/api/users/")) {
            return true;
        }
        
        // 开放页面
        if (requestPath.equals("/") || requestPath.equals("/index") ||
            requestPath.equals("/login") || requestPath.equals("/register")) {
            return true;
        }
        
        return false;
    }
} 